import { useDispatch, useSelector } from 'react-redux'
import { clearCompleted } from '../store/actions/todo'
import classNames from 'classnames'
import { updateActive } from '../store/actions/filter'

export default function TodoFooter() {
  const dispatch = useDispatch()
  const {
    todo,
    filter: { active, arr },
  } = useSelector((state) => state)
  const handleClearCompleted = () => dispatch(clearCompleted())
  // 已完成的数量大于 0 才显示 clear completed 按钮
  const completedLength = todo.filter((item) => item.done).length
  // 点击高亮
  // 1. Redux 中准备一个变量 active
  // 2. 用这个变量和循环时候的数据进行比较，如果一样就应用 selected class
  // 3. 点击的时候，只需要用当前点击的这一项去更新 Redux 中的那个变量 active
  const handleClick = (active) => dispatch(updateActive(active))
  return (
    <>
      {todo.length > 0 && (
        <footer className='footer'>
          <span className='todo-count'>
            <strong>{todo.length - completedLength}</strong> item left
          </span>
          <ul className='filters'>
            {arr.map((item) => (
              <li key={item} onClick={() => handleClick(item)}>
                <a
                  className={classNames({
                    selected: active === item,
                  })}
                  href='#/'
                >
                  {item}
                </a>
              </li>
            ))}
          </ul>
          {completedLength > 0 && (
            <button className='clear-completed' onClick={handleClearCompleted}>
              Clear completed
            </button>
          )}
        </footer>
      )}
    </>
  )
}
